﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VietThuongLMS.Areas.Admin.Models;
using System.Web.Security;
using VietThuongLMS.Services;

///Author: NHDuc 
namespace VietThuongLMS.Areas.Admin.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Admin/Home/

        public ActionResult Index()
        {
            if (!Request.IsAuthenticated)
                return RedirectToAction("Login", "Home", new { area = "Admin" });
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LogOnModel model, string returnUrl)//FormCollection form)
        {
            if (ModelState.IsValid)
            {
                //if (NewsLetterService.SignIn(model.UserName, FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "md5")))
                //AccountService service = new AccountService();
                //if (service.SignIn(model.UserName, model.Password))
                if (AccountService.SignIn(model.UserName, FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "md5")))
                //if (true)
                {
                    if (String.IsNullOrEmpty(model.UserName)) throw new ArgumentException("Value cannot be null or empty.", "userName");

                    TaiKhoan account = AccountService.GetAccountByName(model.UserName);
                    if(account != null && (account.MaLoaiTaiKhoan == "HocVien"
                            || account.MaLoaiTaiKhoan == "GiaoVien"))
                        return RedirectToAction("Index", "Home", new { area = "" });

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home", new { area = "Admin" });
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Tên tài khoản hoặc mật khẩu không đúng.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View();
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home", new { area = "Admin" });
        }

    }
}
